<template>
  <div class="fee-rule-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>费用规则管理</span>
          <el-button type="primary" @click="handleAdd">新增规则</el-button>
        </div>
      </template>
      
      <el-table
        :data="feeRules"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="规则名称" prop="ruleName" />
        <el-table-column label="货物类型" prop="cargoType" />
        <el-table-column label="区域ID" prop="areaId" />
        <el-table-column label="基本费率(元/天)" prop="dailyRate">
          <template #default="scope">
            {{ scope.row.dailyRate.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="最低收费(元)" prop="minimumCharge">
          <template #default="scope">
            {{ scope.row.minimumCharge.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="生效日期">
          <template #default="scope">
            {{ formatDate(scope.row.effectiveDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="ruleForm" label-width="120px" :rules="formRules" ref="ruleFormRef">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称"></el-input>
        </el-form-item>
        <el-form-item label="货物类型" prop="cargoType">
          <el-select v-model="ruleForm.cargoType" placeholder="请选择货物类型">
            <el-option label="集装箱" value="集装箱"></el-option>
            <el-option label="散货" value="散货"></el-option>
            <el-option label="液体" value="液体"></el-option>
            <el-option label="件杂货" value="件杂货"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用区域" prop="areaId">
          <el-select v-model="ruleForm.areaId" placeholder="请选择适用区域">
            <el-option 
              v-for="area in portAreas" 
              :key="area.areaId" 
              :label="`${area.areaCode} - ${area.areaName}`" 
              :value="area.areaId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本费率(元/天)" prop="dailyRate">
          <el-input-number v-model="ruleForm.dailyRate" :min="0" :precision="2" :step="0.5"></el-input-number>
        </el-form-item>
        <el-form-item label="最低收费(元)" prop="minimumCharge">
          <el-input-number v-model="ruleForm.minimumCharge" :min="0" :precision="2" :step="10"></el-input-number>
        </el-form-item>
        <el-form-item label="生效日期" prop="effectiveDate">
          <el-date-picker
            v-model="ruleForm.effectiveDate"
            type="date"
            placeholder="选择生效日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'FeeRuleList',
  setup() {
    const store = useStore()
    const feeRules = ref([])
    const portAreas = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增费用规则')
    const ruleFormRef = ref(null)
    
    // 费用规则表单数据
    const ruleForm = reactive({
      ruleId: null,
      ruleName: '',
      cargoType: '',
      areaId: null,
      dailyRate: 0,
      minimumCharge: 0,
      effectiveDate: new Date().toISOString().split('T')[0]
    })
    
    // 表单验证规则
    const formRules = {
      ruleName: [
        { required: true, message: '请输入规则名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      cargoType: [
        { required: true, message: '请选择货物类型', trigger: 'change' }
      ],
      areaId: [
        { required: true, message: '请选择适用区域', trigger: 'change' }
      ],
      dailyRate: [
        { required: true, message: '请输入基本费率', trigger: 'blur' }
      ],
      minimumCharge: [
        { required: true, message: '请输入最低收费', trigger: 'blur' }
      ],
      effectiveDate: [
        { required: true, message: '请选择生效日期', trigger: 'change' }
      ]
    }
    
    const fetchFeeRules = async () => {
      loading.value = true
      try {
        await store.dispatch('fetchFeeRules')
        feeRules.value = store.getters.feeRules
        console.log('获取到的费用规则数据:', feeRules.value)
      } catch (error) {
        console.error('获取费用规则失败:', error)
        ElMessage.error('获取费用规则失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取港口区域列表
    const fetchPortAreas = async () => {
      try {
        await store.dispatch('fetchPortAreas')
        portAreas.value = store.getters.portAreas
      } catch (error) {
        console.error('获取港口区域失败:', error)
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      return dateString
    }
    
    // 重置表单
    const resetForm = () => {
      ruleForm.ruleId = null
      ruleForm.ruleName = ''
      ruleForm.cargoType = ''
      ruleForm.areaId = null
      ruleForm.dailyRate = 0
      ruleForm.minimumCharge = 0
      ruleForm.effectiveDate = new Date().toISOString().split('T')[0]
      if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
      }
    }
    
    const handleAdd = () => {
      dialogTitle.value = '新增费用规则'
      resetForm()
      dialogVisible.value = true
    }
    
    const handleEdit = (rule) => {
      dialogTitle.value = '编辑费用规则'
      Object.assign(ruleForm, rule)
      dialogVisible.value = true
    }
    
    const handleDelete = (rule) => {
      ElMessageBox.confirm(
        `确认删除规则"${rule.ruleName}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.delete(`fee-rules/${rule.ruleId}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchFeeRules()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除费用规则失败:', error)
          // 显示后端返回的具体错误信息
          if (error.response && error.response.data) {
            ElMessage.error(error.response.data.message || '删除费用规则失败')
          } else {
            ElMessage.error('删除费用规则失败')
          }
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!ruleFormRef.value) return
      
      try {
        await ruleFormRef.value.validate()
        
        if (ruleForm.ruleId) {
          // 编辑现有规则
          const response = await axios.put(`fee-rules/${ruleForm.ruleId}`, ruleForm)
          if (response.data.code === 200) {
            ElMessage.success('更新费用规则成功')
            dialogVisible.value = false
            fetchFeeRules()
          } else {
            ElMessage.error(response.data.message || '更新费用规则失败')
          }
        } else {
          // 新增规则
          const response = await axios.post('fee-rules', ruleForm)
          if (response.data.code === 200) {
            ElMessage.success('添加费用规则成功')
            dialogVisible.value = false
            fetchFeeRules()
          } else {
            ElMessage.error(response.data.message || '添加费用规则失败')
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }
    
    onMounted(() => {
      fetchFeeRules()
      fetchPortAreas()
    })
    
    return {
      feeRules,
      portAreas,
      loading,
      dialogVisible,
      dialogTitle,
      ruleForm,
      ruleFormRef,
      formRules,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      formatDate
    }
  }
}
</script>

<style scoped>
.fee-rule-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>